#include <header.h>
#include "RequestParameter.h"
#include "Constants.h"

RequestParameter* createNode(const char* arg) {
    RequestParameter* newNode = (RequestParameter*)malloc(sizeof(RequestParameter));
    if (!newNode) {
        perror("Failed to allocate memory");
        exit(EXIT_FAILURE);
    }
    strncpy(newNode->argv, arg, BUFF_SIZE - 1);
    newNode->argv[BUFF_SIZE - 1] = '\0'; // Ensure null-termination
    newNode->next = NULL;
    return newNode;
}

void freeLinkedList(RequestParameter* head) {
    RequestParameter* temp;
    while (head != NULL) {
        temp = head;
        head = head->next;
        free(temp);
    }
}
void printLinkedList(RequestParameter* head) {
    RequestParameter* temp = head;
    while (temp != NULL) {
        printf("Parameter: %s\n", temp->argv);
        temp = temp->next;
    }
}

void appendNode(RequestParameter** head, const char* arg) {
    RequestParameter* newNode = createNode(arg);
    if (*head == NULL) {
        *head = newNode;
    } else {
        RequestParameter* temp = *head;
        while (temp->next != NULL) {
            temp = temp->next;
        }
        temp->next = newNode;
    }
}
RequestParameter* createLinkedList(int numElements, ...) {
    RequestParameter* head = NULL;
    va_list args;
    va_start(args, numElements);
    
    for (int i = 0; i < numElements; ++i) {
        const char* arg = va_arg(args, const char*);
        appendNode(&head, arg);
    }
    
    va_end(args);
    return head;
}


/**
 * @brief 传入需要发送的参数链表
*/
void sendLinkedList(int socketfd, RequestParameter* head) {
    RequestParameter* temp = head;
    while (temp != NULL) {
        // printf("Parameter: %s\n", temp->argv);
        send(socketfd, temp->argv, BUFF_SIZE, MSG_NOSIGNAL);
        temp = temp->next;
    }
}

/**
 * @brief 传入需要接收的参数个数，接收后返回参数链表的头指针
*/
RequestParameter *recvLinkedList(int socketfd, int argcnt) {
    RequestParameter* head = NULL;

    for(int i = 0; i < argcnt; i++){
        char buff[BUFF_SIZE];
        memset(buff, 0, sizeof buff);
        recv(socketfd, buff, BUFF_SIZE, MSG_WAITALL);

        appendNode(&head, buff);
    }
    return head;
}